# from .views import blue
from flask import Blueprint, request, jsonify
from werkzeug.utils import secure_filename

from .Cmod import *
from .Cmod_pic import *
from .Cmod_user import *
from .Cmod_express import *
blue_pic = Blueprint('pic', __name__)


# 上传图片返回URL
@blue_pic.route('/api/upload/pics', methods=['POST', 'GET'])
def upload_image():
    if request.method == 'GET':
        return {'message': '错误的请求方式'}, 405
    imageUrls = []
    if 'image0' not in request.files:
        return jsonify({'success': False, 'error': 'No image files'}), 400

    data = request.files
    print(data)
    files = request.files.getlist('image0')  # 获取第一个文件列表
    print(files)
    for i, file in enumerate(files):
        filename = secure_filename(file.filename)
        temporary_path = os.path.join('/', filename)
        file.save(temporary_path)
        print(temporary_path, '    ;1')
        endpoint = 'oss-cn-beijing.aliyuncs.com'
        bucket_name = 'the-design'
        directory1 = '/'
        file_name1 = unique_filename(filename)
        print(file_name1, '    ;2')
        if file_name1.startswith('/'):
            file_name1 = file_name1[1:]
            print(file_name1, '    ;3')

        os.makedirs(os.path.dirname(directory1), exist_ok=True)
        # 从环境变量中获取OSS的认证信息
        oss_access_key_id = os.environ.get('OSS_ACCESS_KEY_ID')
        oss_access_key_secret = os.environ.get('OSS_ACCESS_KEY_SECRET')
        try:
            # 创建Auth对象进行认证
            auth = oss2.Auth(oss_access_key_id, oss_access_key_secret)
            bucket = oss2.Bucket(auth, endpoint, bucket_name)

            # 上传文件到OSS
            object_key1 = '{}'.format(file_name1)  # 确保这是OSS上的有效路径
            bucket.put_object_from_file(object_key1, temporary_path)

            # 构建URL
            url = f'https://{bucket_name}.{endpoint}/{object_key1}'

            # 准备返回的数据
            data_now = {
                'url': url,
                'num': i,
                'success': True
            }
            # 将图片的url添加到列表中
            imageUrls.append(data_now)

        except Exception as e:
            # 处理异常
            data_now = {
                'num': i,
                'success': False
            }
            imageUrls.append(data_now)
            print(f'Error uploading {filename}: {e}')

        finally:
            # 删除临时文件
            if os.path.exists(temporary_path):
                os.remove(temporary_path)

    # 准备并返回最终的响应
    response = {
        'success': True,
        'imageUrl': imageUrls
    }
    # 返回结果和图片URL
    return jsonify(response), 200